#include<strings.h>
#include<string.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
using namespace std;
//类当中的非静态成员函数：第一个参数为隐藏的this指针
//  不需要用户显示传入，不能在声明的时候显示写，可以在函数当中显示使用，只能使用对象去调用
//类当中的静态成员函数：没有隐藏的this指针作为参数，可以使用类域/对象去调用
class Sock
{
public:
    static int Socket()
    {
        int sock = socket(AF_INET,SOCK_STREAM,0);
        if(sock >= 0)
        {
          LOG(NOMAL) <<"socket create success " << endl;
          return sock;
        }
        LOG(FATAL) <<"socket create error" << endl;
        return -1;
    }
    static void Bind(int sock,int port)
    {
      struct sockaddr_in local;
      socklen_t len = sizeof(local);
      bzero(&local,len);
      local.sin_addr.s_addr = INADDR_ANY;
      local.sin_port = htons(port);//主机字节序=>网络字节序
      local.sin_family = AF_INET;
      if(bind(sock,(struct sockaddr*)&local,len) < 0)
      {
        LOG(FATAL) <<"bind error " << endl;
      }
      LOG(NOMAL) <<"bind success" << endl;
    }
    static void Listen(int sock)
    {
      if(listen(sock,5) < 0)
      {
        LOG(FATAL) <<"listen sock set error" << endl;
      }
      LOG(NOMAL) <<"sock set listen status" <<"\n";
    }
    static int Accept(int sock)
    {
      struct sockaddr_in peer;
      socklen_t len = sizeof(peer);
      bzero(&peer,len);
      int fd = accept(sock,(struct sockaddr*)&peer,&len);
      if(fd < 0)
      {
        LOG(ERROR) <<"accept error" << endl;
      }
      LOG(NOMAL) <<"accpet success !" << "\n";
      char* peer_ip = inet_ntoa(peer.sin_addr);
      int peer_port = ntohs(peer.sin_port);
      LOG(NOMAL) << "peer note  ip:" << peer_ip <<"  peer_port: " <<peer_port <<"\n";
      return fd;
    }
};
